package nvshens;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Connection;
import org.jsoup.Jsoup;

import nvshens.bean.NsSingle;

public class NsRunnable implements Runnable {
	private NsSingle nsSingle;
	private String savePath;

	public NsRunnable(NsSingle nsSingle, String savePath) {
		this.nsSingle = nsSingle;
		this.savePath = savePath;
	}

	@Override
	public void run() {
		if (Objects.isNull(nsSingle)) {
			return;
		}

		for (Integer i = 1; i < nsSingle.getNum(); i++) {
			try {
				String downUrl = String.format(nsSingle.getPicUrl(), i);
				long millis = TimeUnit.SECONDS.toMillis(10);
				Connection.Response response = Jsoup.connect(downUrl).timeout((int) millis).referrer(nsSingle.getPageUrl()).ignoreContentType(Boolean.TRUE).execute();
				BufferedInputStream inputStream = response.bodyStream();
				String basePath = StringUtils.join(new String[] { savePath, nsSingle.getSavePath() }, "/");
				FileUtils.copyInputStreamToFile(inputStream, Paths.get(basePath, i + nsSingle.getExtName()).toFile());
				inputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
				System.out.println("下载失败{}" + nsSingle.toString());
			}
		}

	}
}
